﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RedSand.Site.Models;
using RedSand.Web.Mvc;
using System.Web.Security;

namespace RedSand.Site.Controllers
{
    public class AccountController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Manager()
        {
            return View(new ManagerModel { Title = "Account manager" });
        }
        [AjaxOrChildAction]
        public ActionResult List(SearchUsersModel searchModel, int? page)
        {
            int Total = 0;
            List<UserInfo> list = RsDataManager.GetList<UserInfo>("UserSearch", searchModel, page ?? 1, 10, ref Total);
            if (list != null) list = list.Where(item => item.Username != "admin").ToList();
            ViewBag.TotalRecord = Total - 1;
            ViewBag.RouteValues = searchModel;
            return PartialView(list);
        }
        [HttpGet, AjaxOrChildAction]
        public ActionResult Create()
        {
            return PartialView();
        }
        [HttpPost, AjaxOrChildAction]
        public ActionResult Create(UserInfo info, string ConfirmPassword, string[] Check)
        {
            if (ModelState.IsValid)
            {
                if (info.Password != ConfirmPassword)
                {
                    return AjaxMessage("Password not match");
                }
                if (RsDataManager.ExecuteGetReturn("UserCheckUser", new { UserID = 0, UserName = info.Username, Email = info.Email }) > 0)
                {
                    return AjaxMessage("Username or email is in use");
                }
                info.JoinDate = DateTime.Now;
                info.Password = RedSand.Web.Security.RsEncryption.GetMd5Hash(info.Password);
                if (RsDataManager.Save("UserSave", info, new { RoleIDs = "[" + string.Join("][", Check ?? new string[0]) + "]" })>0)
                {
                    AddMessage(Message.CreateSuccess);
                    return RedirectToAction("List");
                }
                return AjaxMessage(Message.CreateError);
            }
            return AjaxModelError();
        }
        [HttpGet, AjaxOrChildAction]
        public ActionResult Edit(int id)
        {
            return PartialView(RsDataManager.GetInfo<UserInfo>("UserGetInfo", "UserID", id));
        }
        [HttpPost, AjaxOrChildAction]
        public ActionResult Edit(UserInfo info, string[] Check)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.ExecuteGetReturn("UserCheckUser", new { UserID = info.UserID, UserName = info.Username, Email = info.Email }) > 1)
                {
                    return AjaxMessage("Email is in use");
                }
                if (RsDataManager.Save("UserSave", info, new { RoleIDs = "[" + string.Join("][", Check ?? new string[0]) + "]" })>0)
                {
                    AddMessage(Message.UpdateSuccess);
                    return RedirectToAction("List");
                }
                return AjaxMessage(Message.UpdateError);
            }
            return AjaxModelError();
        }
        [AjaxOrChildAction]
        public ActionResult Delete(int id)
        {
            UserInfo info = RsDataManager.GetInfo<UserInfo>("UserGetInfo", "UserID", id);
            if (RsDataManager.Delete("UserDelete", "UserID", id))
            {
                if (info.Username == User.Identity.Name)
                {
                    FormsAuthentication.SignOut();
                    AddMessage("Your account has been delete");
                    return RedirectToLogin();
                }
                AddMessage(Message.DeleteSuccess);
                return RedirectToAction("List");
            }
            return AjaxMessage(Message.DeleteError);
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserID = RsDataManager.ExecuteGetReturn("UserValidate", new { UserName = model.Username, Password = RedSand.Web.Security.RsEncryption.GetMd5Hash(model.Password) });
                if (UserID > 0)
                {
                    FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1)
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return Redirect("/admin");
                    }
                }
                else
                {
                    AddMessage("Username or password wrong");
                }
            }
            else
            {
                AddMessage("Username or password wrong");
            }
            return View();
        }
        
        public ActionResult Logout()
        {
            Session.RemoveAll();
            FormsAuthentication.SignOut();
            return Redirect("/");
        }
        [HttpGet, AjaxOrChildAction]
        public ActionResult ChangePassword(int? id)
        {
            ViewBag.UserID = id ?? UserID;
            return PartialView();
        }
        [HttpPost, AjaxOrChildAction]
        public ActionResult ChangePassword(ChangePasswordModel model, int UserID)
        {
            if (ModelState.IsValid)
            {
                if (model.NewPassword != model.ConfirmPassword)
                {
                    return AjaxMessage("Password not match");
                }
                string oldPass = RedSand.Web.Security.RsEncryption.GetMd5Hash(model.OldPassword);
                string newPass = RedSand.Web.Security.RsEncryption.GetMd5Hash(model.NewPassword);
                if (RsDataManager.ExecuteGetReturn("UserChangePassword", new { OldPassword = oldPass, NewPassword = newPass }) > 0)
                {
                    return AjaxMessage("Old password wrong");
                }
                return Json("");
            }
            return PartialView();
        }

        [Authorize]
        public ActionResult Profile()
        {
            return View(RsDataManager.GetInfo<UserInfo>("UserGetInfo", new { UserName = User.Identity.Name }));
        }

        [HttpGet, AjaxOrChildAction]
        public ActionResult ChangeProfile()
        {
            return PartialView(RsDataManager.GetInfo<UserInfo>("UserGetInfo", new { UserName = User.Identity.Name }));
        }
        [HttpPost, AjaxOrChildAction]
        public ActionResult ChangeProfile(UserInfo info)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.ExecuteGetReturn("UserCheckUser", new { UserID = info.UserID, UserName = info.Username, Email = info.Email }) > 1)
                {
                    return AjaxMessage("Email is in use");
                }
                info.Username = User.Identity.Name;
                info.UserID = UserID;
                List<RoleCheckListModel> listRole = RsDataManager.GetList<RoleCheckListModel>("RoleGetRoleForUser", new { UserID = info.UserID });
                if (listRole != null) listRole = listRole.Where(item => item.Check).ToList();
                string[] roleIDs = new string[listRole.Count];
                for (int i = 0; i < listRole.Count; i++)
                {
                    roleIDs[i] = listRole[i].RoleID.ToString();
                }
                if (RsDataManager.Save("UserSave", info)>0)
                {
                    return RedirectToAction("Profile");
                }
                return AjaxMessage(Message.UpdateError);
            }
            return AjaxModelError();
        }
    }
}
